const Koa = require("Koa")
const KoaRouter = require("koa-router")
const KoaStaticCache = require("koa-static-cache")
const http = require("http")
const socketIo = require("socket.io")


const app = new Koa();
const router = new KoaRouter();
const server = http.createServer(app.callback())
const io = socketIo(server)


app.use(KoaStaticCache('./public', {
    prefix: '/public',
    gzip: true,
    dynamic: true
}));

io.on('connection',socket=>{
    console.log("有人连接了",socket.id)
    socket.on('data',data=>{
        console.log(data)
        // 发送给除了当前用户的其他用户
        socket.broadcast.emit('message', {
            socketId: socket.id,
            value: data,
            time:getTime(),
        });
        // 再发一份给自己
        socket.emit('message', {
                socketId:socket.id,
                value:data,
                time:getTime()
            });
    })
})

app.use(router.routes())
server.listen("8888",()=>{
	console.log("启动成功: http://localhost:8888")
})

function getTime() {
    var today=new Date();
    var y=today.getFullYear();
    var m=today.getMonth();
    var d=today.getDate();
    var h=today.getHours();
    var i=today.getMinutes();
    var s=today.getSeconds();// 在小于10的数字钱前加一个‘0’
    m=m+1;
    return y+"-"+m+"-"+d+" "+h+":"+i+":"+s
}